const express = require('express');
const axios = require('axios');

const router = express.Router();

// GET /proxy/image?url=<encoded>
router.get('/image', async (req, res) => {
  try {
    const { url } = req.query || {};
    if (!url || typeof url !== 'string') {
      return res.status(400).json({ code: '40000', message: '缺少必需参数 url', data: null });
    }

    let target;
    try {
      target = new URL(url);
    } catch (_) {
      return res.status(400).json({ code: '40001', message: 'url 非法', data: null });
    }

    if (!/^https?:$/i.test(target.protocol)) {
      return res.status(400).json({ code: '40002', message: '仅支持 http/https 协议', data: null });
    }

    // 透传图片，限制超时
    const upstream = await axios.get(target.toString(), {
      responseType: 'stream',
      timeout: 10000,
      // 可根据需要添加更多头部，如 UA
      headers: {
        'User-Agent': 'suniu-image-proxy/1.0',
        'Accept': 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
      },
      validateStatus: () => true,
      maxContentLength: 15 * 1024 * 1024, // 15MB
    });

    if (upstream.status >= 400) {
      return res.status(upstream.status).json({
        code: String(upstream.status),
        message: `上游图片请求失败: ${upstream.status}`,
        data: null,
      });
    }

    // 设置允许跨域及缓存
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
    res.setHeader('Cache-Control', 'public, max-age=86400'); // 1 天

    const contentType = upstream.headers['content-type'] || 'image/jpeg';
    const contentLength = upstream.headers['content-length'];
    res.setHeader('Content-Type', contentType);
    if (contentLength) res.setHeader('Content-Length', contentLength);

    upstream.data.on('error', () => {
      if (!res.headersSent) {
        res.status(502).json({ code: '50200', message: '图片流读取失败', data: null });
      } else {
        res.destroy();
      }
    });

    upstream.data.pipe(res);
  } catch (err) {
    console.error('图片代理失败:', err?.message);
    res.status(500).json({ code: '50000', message: '图片代理失败', data: null });
  }
});

module.exports = router;
